package cn.feizhu.aimarket.ai.workflow.node;

import cn.feizhu.aimarket.ai.workflow.model.constant.WorkflowControlConstant;
import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.action.NodeAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;

import java.util.Map;

/**
 * 智能判断节点
 * 判断用户输入是否符合智能内容生成的要求
 *
 * @author feizhu
 * @since 2025/10/16
 */
public class SmartJudgeNode implements NodeAction {

    private static final Logger logger = LoggerFactory.getLogger(SmartJudgeNode.class);

    private final ChatClient writerRouterClient;

    public SmartJudgeNode(ChatClient writerRouterClient) {
        this.writerRouterClient = writerRouterClient;
    }


    @Override
    public Map<String, Object> apply(OverAllState state) {
        logger.info("=== 智能判断节点开始执行 ===");

        try {
            // 获取用户输入
            String userInput = (String) state.value(WorkflowControlConstant.USER_INPUT)
                    .orElse("");

            logger.info("用户输入: {}", userInput);

            if (userInput.trim().isEmpty()) {
                logger.warn("用户输入为空，判断为FAIL");
                return Map.of(WorkflowControlConstant.JUDGE_RESULT, WorkflowControlConstant.BRANCH_FAIL);
            }

            // 使用AI进行智能判断 这里会拦截一些非法请求的
            String judgeResult = writerRouterClient.prompt()
                    .user(userInput)
                    .call()
                    .content();
            logger.info("AI判断结果: {}", judgeResult);

            // 解析判断结果
            String finalResult;
            if (judgeResult.trim().toUpperCase().contains("PASS")) {
                finalResult = WorkflowControlConstant.BRANCH_PASS;
                logger.info("智能判断通过，继续执行工作流");
            } else {
                finalResult = WorkflowControlConstant.BRANCH_FAIL;
                logger.info("智能判断失败，需要用户重新输入");
            }
            state.value(WorkflowControlConstant.JUDGE_RESULT, finalResult);
            return Map.of(WorkflowControlConstant.JUDGE_RESULT, finalResult);

        } catch (Exception e) {
            logger.error("智能判断节点执行异常", e);
            // 异常情况下默认为失败
            return Map.of(WorkflowControlConstant.JUDGE_RESULT, WorkflowControlConstant.BRANCH_FAIL);
        } finally {
            logger.info("=== 智能判断节点执行完成 ===");
        }
    }
}
